package com.example.translateappjava.Activity.HomeFragmentActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.translateappjava.Activity.MainActivity;
import com.example.translateappjava.DataBase.DatabaseHelper;
import com.example.translateappjava.DataBase.HistoryAdapter;
import com.example.translateappjava.Fragment.HomeFragment;
import com.example.translateappjava.R;
import com.example.translateappjava.Service.DiabetesFoodAdvisor;
import com.google.android.material.progressindicator.CircularProgressIndicator;
import com.google.android.material.progressindicator.LinearProgressIndicator;

import java.util.ArrayList;

public class SearchActivity extends AppCompatActivity {

    //-------------
    DatabaseHelper databaseHelper;
    ListView historyListView;
    ArrayList<String> historyList;
    HistoryAdapter adapter;
    //----------------
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_search);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        //-----------
        databaseHelper = new DatabaseHelper(this);
        historyListView = findViewById(R.id.listView);
        historyList = new ArrayList<>();
        adapter = new HistoryAdapter(this, historyList);
        historyListView.setAdapter(adapter);
        // 设置ListView的点击事件监听器
        historyListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 获取点击项的内容
                String selectedSearchText = historyList.get(position);
                // 将内容设置到SearchView的查询文本中
                SearchView searchView = findViewById(R.id.searchView);
                searchView.setQuery(selectedSearchText, true);
            }
        });

        Button clearButton = findViewById(R.id.button);
        clearButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 调用DatabaseHelper的clearHistory方法清空历史记录
                databaseHelper.clearHistory();
                // 清空历史列表并通知适配器更新
                historyList.clear();
                adapter.notifyDataSetChanged();
            }
        });
        //--------------
        Intent intent = getIntent();
        String query = intent.getStringExtra("query");
        SearchView searchView = findViewById(R.id.searchView);
        @SuppressLint({"MissingInflatedId", "LocalSuppress"}) LinearLayout layout = findViewById(R.id.LoadingLinear);
        @SuppressLint({"MissingInflatedId", "LocalSuppress"}) ConstraintLayout constraintLayout = findViewById(R.id.constraintLayout2);
        constraintLayout.setVisibility(View.VISIBLE);
        layout.setVisibility(View.GONE);
        if (query != null){
            searchView.setQuery(query,false);
            searchView.setQueryHint(query);
            startQuery(query);
            showLoading();
        }
        MainActivity.setBackGroundColor(SearchActivity.this);
        searchView.setQueryHint("请输入食物名称");
        /**
         * 开始时获取homefragment的传值
         * 不为空直接进行搜索
         */




        //        CircularProgressIndicator circularProgressIndicator = findViewById(R.id.i2);
//        LinearProgressIndicator linearProgressIndicator = findViewById(R.id.i1);
//        circularProgressIndicator.setVisibility(View.GONE);
//        linearProgressIndicator.setVisibility(View.GONE);
        /***
         * 这里实现搜索页面
         *
         */
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
//                // 用户提交搜索时执行的操作
//                // 例如，你可以在这里开始执行搜索
//                DiabetesFoodAdvisor advisor = new DiabetesFoodAdvisor(SearchActivity.this);
//                // 假设您已经有了食物识别结果
//                String foodRecognitionResult = query;
//                // 调用 processFoodRecognitionResult 方法处理识别结果
//                advisor.processFoodRecognitionResult(foodRecognitionResult);
                CircularProgressIndicator circularProgressIndicator = findViewById(R.id.i2);
                LinearProgressIndicator linearProgressIndicator = findViewById(R.id.i1);


                circularProgressIndicator.setVisibility(View.VISIBLE);
                linearProgressIndicator.setVisibility(View.VISIBLE);
                startQuery(query);
                layout.setVisibility(View.VISIBLE);
                constraintLayout.setVisibility(View.GONE);

                //--------------
                boolean isInserted = databaseHelper.insertData(query);
                if (isInserted) {
                    updateHistoryList(); // 如果插入了新数据，则更新列表
                    databaseHelper.insertData(query); // 将搜索内容插入数据库
                }

                //--------------------
                return false;
            }
            /**
             * 文字变化暂不做处理
             *
             * */
            @Override
            public boolean onQueryTextChange(String newText) {
                // 用户输入文字发生变化时执行的操作
                // 例如，你可以在这里开始显示搜索建议
                return false;
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
//        circularProgressIndicator.setVisibility(View.GONE);
//        linearProgressIndicator.setVisibility(View.GONE);
        //更新搜索历史
        updateHistoryList();
    }



    public void startQuery(String query){
        DiabetesFoodAdvisor advisor = new DiabetesFoodAdvisor(SearchActivity.this);
        // 假设您已经有了食物识别结果
        String foodRecognitionResult = query;
        // 调用 processFoodRecognitionResult 方法处理识别结果
        advisor.processFoodRecognitionResult(foodRecognitionResult);
    }

    public void showLoading(){
        @SuppressLint({"MissingInflatedId", "LocalSuppress"}) LinearLayout layout = findViewById(R.id.LoadingLinear);
        @SuppressLint({"MissingInflatedId", "LocalSuppress"}) ConstraintLayout constraintLayout = findViewById(R.id.constraintLayout2);
        CircularProgressIndicator circularProgressIndicator = findViewById(R.id.i2);
        LinearProgressIndicator linearProgressIndicator = findViewById(R.id.i1);
        circularProgressIndicator.setVisibility(View.VISIBLE);
        linearProgressIndicator.setVisibility(View.VISIBLE);
        layout.setVisibility(View.VISIBLE);
        constraintLayout.setVisibility(View.GONE);
    }
    public void showSearch(){
        @SuppressLint({"MissingInflatedId", "LocalSuppress"}) LinearLayout layout = findViewById(R.id.LoadingLinear);
        @SuppressLint({"MissingInflatedId", "LocalSuppress"}) ConstraintLayout constraintLayout = findViewById(R.id.constraintLayout2);
        CircularProgressIndicator circularProgressIndicator = findViewById(R.id.i2);
        LinearProgressIndicator linearProgressIndicator = findViewById(R.id.i1);
        circularProgressIndicator.setVisibility(View.VISIBLE);
        linearProgressIndicator.setVisibility(View.VISIBLE);
        layout.setVisibility(View.VISIBLE);
        constraintLayout.setVisibility(View.VISIBLE);
    }
    //------------------------
    private void updateHistoryList() {
        historyList.clear();
        historyList.addAll(databaseHelper.getAllData());
        adapter.notifyDataSetChanged();
    }
}